package com.hsmw.api.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.UUID;

/**
 * 日志追踪
 *
 * @author
 */
@WebFilter(urlPatterns = "/*")
@Order(1)
@Slf4j
public class TraceIdFilter implements Filter {

	/**
	 * TraceId常量
	 */
	private static final String TRACE_ID = "traceId";

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		String traceId = servletRequest.getParameter(TRACE_ID);
		// 为空设置默认值
		if (StringUtils.isEmpty(traceId)) {
			traceId = UUID.randomUUID().toString();
		}
		// 在MDC中放入traceId
		MDC.put(TRACE_ID, traceId);

		filterChain.doFilter(servletRequest, servletResponse);
	}


	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}
}
